/**
 * WeChat Mini Porgram vPush SDK
 * -------------
 * 艾码汇基于 WordPress 系统创建
 * 网址：https://www.imahui.com
 * 更新时间：2019/10/11
 * -------------
 * 使用方法：
 * app.js中引入此模块，然后初始化：App({ vPush: new vPush('你的API服务接口地址'), ..})
 * 比如：new vPush("https://www.weitimes.com")
 */

class vPush {
  constructor(url) {
    if (!url) {
      throw new Error("[Error] 设置您的API服务接口地址");
    }
    this.HOST = `${url}/wp-json`;
    this.init();
  }
  _request (uri, data) {
    let url = `${this.HOST}${uri}`
    console.log(data)
    return new Promise(function(resolve, reject) {
      wx.request({
        url,
        method: 'POST',
        data,
        success: function(res) {
          console.log(res);
          resolve(res.data);
        },
        fail: function(err) {
          console.log(err);
          reject(err);
        }
      })
    });
  }
  
  init( ) {
    let that = this
    let cache = wx.getStorageSync('_USER_OPENID');
    if (cache && cache.length > 10) { 
      return cache; 
    }
    wx.login({
      success: function(res) {
        //console.log('code', res.code);
        that._request('/mp/v2/user/openid', {code: res.code}).then(ret => {
          console.warn('[vPush.OpenID] ', ret.openid);
          wx.setStorageSync('_USER_OPENID', ret.openid);
        }, err => {
          console.log(err);
        });
      },
      fail: function(err) {
        console.log(err)
      }
    })

  }
  addFormId( template, status ) {
    // 获取当前页面地址
    let page = getCurrentPages()[0].route;
    let openID = wx.getStorageSync('_USER_OPENID');
    let systemInfo = wx.getSystemInfoSync();
    this._request('/mp/v2/subscribe', {
      openid: openID,
      template: template,
      status: status,
      pages: page,
      platform: systemInfo.platform,
      program: 'WeChat'
    }).then(ret => {
      console.warn(ret.message);
    }).catch(err => {
      console.warn(err);
    })
  }
}

module.exports = vPush;